<template>
  <div class="page">
    <el-row :gutter="20" style="width: 100%; margin-bottom: 20px">
      <el-col :span="8">
        <el-input
          v-model="state.query.url"
          placeholder="小红书地址"
          clearable
        />
      </el-col>
      <el-col :span="8">
        <el-button type="primary" @click="start">抓取小红书</el-button>
      </el-col>
    </el-row>

    <BtnArea v-if="state.list.length > 0">
      <el-button type="primary" @click="publishFn">批量发布</el-button>
    </BtnArea>

    <Wtable
      v-loading="state.loading"
      :data="state.list"
      :pagination="false"
      :order="false"
      :selection="false"
    >
      <el-table-column prop="user" label="帐号" width="150">
        <template #default="scope">
          {{ scope.row.user.name }}
        </template>
      </el-table-column>
      <el-table-column prop="pics" label="图片" width="500">
        <template #default="scope">
          <el-upload
            :file-list="scope.row.fileList"
            list-type="picture-card"
            :http-request="
              (filePayload) => {
                customRequest(filePayload, scope.row);
              }
            "
            :on-preview="handlePictureCardPreview"
            :on-remove="
              (uploadFile) => {
                handlePictureCardRemove(uploadFile, scope.row);
              }
            "
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="标题与内容">
        <template #default="scope">
          <BtnArea v-if="state.list.length > 0">
            <el-input v-model="scope.row.title"> </el-input>
            <el-button
              type="secondry"
              :loading="scope.row.aiLoading"
              @click="chatWithAiFn(scope.row, 'title')"
              >标题改写</el-button
            >
          </BtnArea>

          <div>
            <div>
              <el-input v-model="scope.row.content" type="textarea" :rows="18">
              </el-input>
            </div>
            <el-button
              type="secondry"
              :loading="scope.row.aiLoading2"
              @click="chatWithAiFn(scope.row, 'content')"
              >内容改写</el-button
            >
          </div>
        </template>
      </el-table-column>
    </Wtable>

    <el-dialog v-model="dialogVisible">
      <img
        style="width: 100%"
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";

import { ElLoading } from "element-plus";
import {
  startCrawler,
  publish,
  uploadImg,
  chatWithAi,
} from "@/api/xiaohongshu";

const state = reactive({
  query: {
    url: "https://www.xiaohongshu.com/explore/60190c50000000000100997e",
  },
  loading: false,
  list: [],
});
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const start = async () => {
  let { data } = await startCrawler(state.query);

  state.list = data.map((item) => {
    item.fileList = item.pics.map((item2) => {
      return {
        name: null,
        url: item2.url,
      };
    });
    return item;
  });
};

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
const handlePictureCardRemove = (uploadFile, row) => {
  if (uploadFile.url.indexOf("http") === 0) {
    // 删除网络图片
    row.fileList = row.fileList.filter((item) => item.uid !== uploadFile.uid);
  } else {
    // 删除手动上传的图片
    row.fileList = row.fileList.filter((item) => item.name !== uploadFile.name);
  }
};
const customRequest = async ({ file, onProgress, onSuccess, onError }, row) => {
  // 创建一个 FormData 对象
  const formData = new FormData();
  formData.append("file", file);
  formData.append("name", row.user.name);

  try {
    let { data } = await uploadImg(formData);

    const hasUpload = row.fileList.find((item) => item.name === data.name);
    if (!hasUpload) {
      row.fileList.push({
        name: data.name,
        url: data.url,
      });
    }
  } catch (error) {
    onError(error);
  }
};

const chatWithAiFn = async (row, field) => {
  let content = row[field];
  if (field === "title") {
    row.aiLoading = true;
    content = `'${content}' 帮我用小红书的语气改写这段话 字数最大20个`;
  } else {
    row.aiLoading2 = true;
    content = `'${content}' 帮我用小红书的语气改写这段话`;
  }
  try {
    const { data } = await chatWithAi({
      content: content,
    });
    if (field === "title") {
      row.aiLoading = false;
    } else {
      row.aiLoading2 = false;
    }

    row[field] = data;
  } catch (error) {
    if (field === "title") {
      row.aiLoading = false;
    } else {
      row.aiLoading2 = false;
    }
  }
};
const publishFn = async () => {
  await publish({
    list: state.list,
  });
};
</script>

<style lang="scss" scoped>
.page {
  padding: 20px;
}
</style>
